<template>
    <el-dialog v-model="visible" draggable :title="title" destroyOnClose width="500px" @close="closeModal" append-to-body>
        <div>
            <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="form.roleName" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item prop="roleKey">
                    <template #label>
                        <span>
                            <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
                                <el-icon><question-filled /></el-icon>
                            </el-tooltip>
                            权限字符
                        </span>
                    </template>
                    <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
                </el-form-item>
                <el-form-item label="角色顺序" prop="roleSort">
                    <el-input-number v-model="form.roleSort" controls-position="right" :min="0" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="form.status">
                        <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="菜单权限">
                    <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
                    <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
                    <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
                    <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menuRef" node-key="id" :check-strictly="!form.menuCheckStrictly" empty-text="加载中，请稍候" :props="{ label: 'label', children: 'children' }"></el-tree>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts">
    import { defineComponent, ref, watch, nextTick, reactive, toRefs, getCurrentInstance, computed } from "vue";
    import { addRole, updateRole } from "@/api/system/role";
    import { treeselect as menuTreeselect } from "@/api/system/menu";
    export default defineComponent({
        props: {
            modelValue: { type: Boolean, default: () => false },
            record: { type: Object, default: () => {} },
            isUpdate: { type: Boolean, default: () => false },
        },
        emits: ["update:modelValue", "close"],
        setup(props, { emit }) {
            const visible = ref<Boolean>(props.modelValue);
            const editorValue = ref();
            const { proxy } = getCurrentInstance() as any;
            const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
            const menuExpand = ref(false);
            const menuNodeAll = ref(false);
            const menuOptions = ref([]);
            const menuRef = ref<any>();
            const roleRef = ref();
            const data: any = reactive({
                form: {},
                rules: {
                    roleName: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
                    roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
                    roleSort: [{ required: true, message: "角色顺序不能为空", trigger: "blur" }],
                },
            });
            const { form, rules } = toRefs(data);

            watch(
                () => props.modelValue,
                (value: any) => {
                    if (value) {
                        if (props.isUpdate) {
                            reset();
                            openModal();
                            handleUpdateGetList();
                        } else {
                            getMenuTreeselect();
                            data.form = {};
                            reset();
                        }
                    } else {
                        visible.value = false;
                        closeModal("model");
                    }
                }
            );
            const title = computed(() => {
                return props.isUpdate ? "修改角色" : "添加角色";
            });
            //    打开弹窗
            const openModal = () => {
                visible.value = true;
                emit("update:modelValue", true);
                return nextTick();
            };
            // 关闭弹窗
            const closeModal = async (type: string = "cancel", data: object = {}) => {
                emit("update:modelValue", false);
                emit("close", { type: type, data: data });
                return nextTick();
            };

            // 取消
            const cancel = () => {
                closeModal();
            };
            /** 重置新增的表单以及其他数据  */
            function reset() {
                if (menuRef.value != undefined) {
                    menuRef.value.setCheckedKeys([]);
                }
                menuExpand.value = false;
                menuNodeAll.value = false;
                form.value = {
                    roleId: undefined,
                    roleName: undefined,
                    roleKey: undefined,
                    roleSort: 0,
                    status: "0",
                    menuIds: [],
                    menuCheckStrictly: true,
                    remark: undefined,
                };
                proxy.resetForm("roleRef");
            }
            /** 查询菜单树结构 */
            function getMenuTreeselect() {
                menuTreeselect().then((response) => {
                    menuOptions.value = response.data;
                });
                openModal();
            }
            /** 树权限（展开/折叠）*/
            function handleCheckedTreeExpand(value: any) {
                let treeList: any = menuOptions.value;
                for (let i = 0; i < treeList.length; i++) {
                    menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
                }
            }
            /** 树权限（全选/全不选） */
            function handleCheckedTreeNodeAll(value: any) {
                menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
            }
            /** 树权限（父子联动） */
            function handleCheckedTreeConnect(value: any) {
                form.value.menuCheckStrictly = value ? true : false;
            }
            /** 所有菜单节点数据 */
            function getMenuAllCheckedKeys() {
                // 目前被选中的菜单节点
                let checkedKeys = menuRef.value.getCheckedKeys();
                // 半选中的菜单节点
                let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
                checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
                return checkedKeys;
            }
            /** 修改角色 */
            function handleUpdateGetList() {
                form.value = props.record.form;
                props.record.roleMenu.then((res: any) => {
                    menuOptions.value = res.menus;
                    let checkedKeys = res.checkedKeys;
                    checkedKeys.forEach((v: any) => {
                        nextTick(() => {
                            menuRef.value?.setChecked(v, true, false);
                        });
                    });
                });
            }

            /** 提交按钮 */
            function submitForm() {
                proxy.$refs["roleRef"].validate((valid: any) => {
                    if (valid) {
                        if (form.value.roleId != undefined) {
                            form.value.menuIds = getMenuAllCheckedKeys();
                            updateRole(form.value).then((response) => {
                                proxy.$modal.msgSuccess("修改成功");
                                closeModal("submit", form.value);
                            });
                        } else {
                            form.value.menuIds = getMenuAllCheckedKeys();
                            addRole(form.value).then((response) => {
                                proxy.$modal.msgSuccess("新增成功");
                                closeModal("submit", form.value);
                            });
                        }
                    }
                });
            }

            return {
                visible,
                cancel,
                closeModal,
                openModal,
                editorValue,
                form,
                rules,
                sys_normal_disable,
                menuExpand,
                menuNodeAll,
                menuOptions,
                handleCheckedTreeExpand,
                handleCheckedTreeNodeAll,
                handleCheckedTreeConnect,
                submitForm,
                title,
                menuRef,
                roleRef,
            };
        },
    });
</script>

<style scoped lang="scss"></style>
